package com.medicalfee.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.medicalfee.dao.StuffInfo;
import com.medicalfee.dao.StuffInfoDAO;

public class SearchStuffController implements Controller {
	private StuffInfoDAO stuffInfoDao;

	public void setStuffInfoDao(StuffInfoDAO stuffInfoDao) {
		this.stuffInfoDao = stuffInfoDao;
	}

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String text = request.getParameter("text");
		String start = request.getParameter("start");
		String limit = request.getParameter("limit");
		int startPage = 0, limitNum = 0;
		if (start != null) {
			startPage = Integer.parseInt(start);
		}
		if (limit != null) {
			limitNum = Integer.parseInt(limit);
		}
		List stuffInfoList = stuffInfoDao.findStuff(text, startPage, limitNum);
		JSONObject json = new JSONObject();
		JSONArray rows = new JSONArray();
		for (int i = 0; i < stuffInfoList.size(); i++) {
			StuffInfo stuffInfo = (StuffInfo) stuffInfoList.get(i);
			JSONObject jobject = JSONObject.fromObject(stuffInfo);
			rows.add(jobject);
		}
		json.put("total", stuffInfoDao.getStuffNumBySearch(text));                                            
		json.put("rows", rows);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(json.toString());
		return null;
	}

}
